<template>
  <div>
    <top-bar></top-bar>
    <left-bar :datas='data'></left-bar>
    <div class="adddrug system">
      <home-bar :currentPage='currentPage'></home-bar>
      <div class="adddrugs system-main">
        <div class="main-position">
          首页 > 药品管理 > 产品种类管理
        </div>
        <div class="main-height"></div>
        <div class="main-mains">
          <div class="main-top-nav">
            <ul>
             <li>
                <router-link to="/druglistai/stockmanagement" @click.native="addPath('/druglistai/stockmanagement','药品管理');determineRouting('stockmanagement')">
                  进货管理
                </router-link>
              </li>
              <li>
                <router-link to="/druglistai/xiajia" @click.native="addPath('/druglistai/xiajia','药品管理');determineRouting('xiajia')">
                  已下架
                </router-link>
              </li>
              <li>
                <router-link to="/druglistai/deleteddrugs" @click.native="addPath('/druglistai/deleteddrugs','药品管理');determineRouting('deleteddrugs')">
                  已删除药品
                </router-link>
              </li>
              <li>
                <router-link to="/druglistai/shortageofdrugs" @click.native="addPath('/druglistai/shortageofdrugs','药品管理');determineRouting('shortageofdrugs')">
                  缺货药品
                </router-link>
              </li>
              <li>
                <router-link to="/druglistai/willexpire" @click.native="addPath('/druglistai/willexpire','药品管理');determineRouting('willexpire')">
                  即将过期
                </router-link>
              </li>
              <li>
                <router-link to="/druglistai/expired" @click.native="addPath('/druglistai/expired','药品管理');determineRouting('expired')">
                  已过期
                </router-link>
              </li>
              <li>
                <router-link to="/druglistai/lackdrug" @click.native="addPath('/druglistai/lackdrug','药品管理');determineRouting('lackdrug')">
                  库存预警
                </router-link>
              </li>
              <li class="active">
                <router-link to="/productcategorymgmt" @click.native="addPath('/productcategorymgmt','药品管理');">
                  产品种类管理
                </router-link>
              </li>
              <li>
                <router-link to="/brandlibrary" @click.native="addPath('/brandlibrary','药品管理');">
                  品牌库
                </router-link>
              </li>
            </ul>
          </div>
          <div class="drugListMain">
            <div class="headOperation">
              <a href="javascript:void(0);" class="OperationA-application" @click="clickAddCategory">申请添加分类</a>
              <div class="turnBack">
                <router-link to="/productcategorymgmt" @click.native="addPath('/productcategorymgmt','药品管理');">返回</router-link>
              </div>
            </div>
            <!--/.headOperation -->
            <div class="drugListTable productCategoryMgmtTable">
              <table>
                <tr>
                  <td>序号</td>
                  <td>分类名称</td>
                  <td>产品类型</td>
                  <td>子类目数量</td>
                  <td>药品数量</td>
                  <td>操作</td>
                </tr>
                <tr v-for="(trading,index) in category_list" :key="index">
                  <td width="100">{{index+1}}</td>
                  <td>{{trading.category_name}}</td>
                  <td>{{trading.type = 1 ? '通用类型' : ''}}</td>
                  <td>{{trading.sub_category_total}}</td>
                  <td>{{trading.medical_total}}</td>
                  <td>
                    <router-link :to="{name:'agentLevelThree',params:{pid:trading.category_id,topid:$route.params.pid}}" @click.native="addPath('/productcategorymgmt/leveltwo/levelthree/'+$route.params.pid,'药品管理');">进入查看</router-link>
                  </td>
                </tr>
              </table>
            </div>
            <div class="pageBotom">
              <div class="pageBotomRight">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage4" :page-sizes="[100, 200, 300, 400]" :page-size="100" layout="total, sizes, prev, pager, next, jumper" :totalNumOfArticle="400">
                </el-pagination>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 弹窗开始 -->
      <div class="system-menban" v-show="showSystemPopup"></div>
      <div class="systemPopup" v-show="showSystemPopup">
        <div class="topTitle">
          <span>{{systemPopupTitle}}</span>
          <i class="el-icon-close system-icon" @click="hideSystemPopup"></i>
        </div>
        <!-- 申请添加分类弹窗 -->
        <div class="ApplicationPopup" v-show="showApplicationPopup">
          <div class="ApplicationPopupInner">
            <div class="ApplicationItem clear">
              <span class="leftTitle">二级分类名称</span>
              <el-input v-model="categoryNameValueTwo" placeholder="请输入内容"></el-input>
            </div>
            <div class="ApplicationItem clear">
              <span class="leftTitle">三级分类名称</span>
              <el-input v-model="categoryNameValueThree" placeholder="请输入内容"></el-input>
            </div>
            <div class="ApplicationItem clear">
              <span>三级分类图片</span>
              <div class="cropper-img clear">
                <div class="cropperBox fl">
                  <vueCropper ref="cropper3" :img="example3.img" :outputSize="example3.outputSize" :canMoveBox="example3.canMoveBox" :canMove="example3.canMove" :autoCrop="example3.autoCrop" :autoCropWidth="example3.autoCropWidth" :autoCropHeight="example3.autoCropHeight"
                    :fixedBox="example3.fixedBox"></vueCropper>
                </div>
                <div class="cropper-img-l fl">
                  <label class="choosePicture" for="uploads">选择图片</label>
                  <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/jpg" @change="uploadImg($event)">
                  <div class="tip">请上传200*200分辨率的图片，<br>支持png,jpeg,jpg格式</div>
                </div>
              </div>
            </div>
            <div class="ApplicationItem clear">
              <span class="leftTitle">药品类型</span>
              <el-select v-model="drugTypeValue" placeholder="请选择">
                <el-option v-for="item in drugTypeOptions" :key="item.id" :label="item.label" :value="item.id">
                </el-option>
              </el-select>
            </div>
            <div class="system-messagebox1-btn clear">
              <div @click="clickSubmit">提交</div>
              <div @click="hideSystemPopup">取消</div>
            </div>
          </div>
        </div>
        <!-- 申请添加分类成功弹窗 -->
        <div class="okPopup" v-show="showApplicationOkPopup">
          <i class="iconfont icon-ok"></i>
          <h3>提交成功</h3>
          <span>提交成功后需进行人工审核，请您耐心等候。</span>
          <div class="system-messagebox1-btn clear">
            <div @click="hideSystemPopup">确定</div>
          </div>
        </div>
      </div>
      <!-- 弹窗结束 -->
    </div>
  </div>
</template>

<script>
import topBar from "../../../public/top";
import leftBar from "../../../public/left";
import homeBar from "../../../public/homebar";
import vueCropper from "vue-cropper";
export default {
  components: {
    leftBar,
    topBar,
    homeBar,
    vueCropper
  },
  data() {
    return {
      data: "drugManagment",
      currentPage: {
        path: "/productcategorymgmt/leveltwo",
        name: "药品管理"
      },
      category_list: [],
      drugTypeOptions: [
        {
          id: 1,
          label: "通用类型"
        }
      ],
      drugTypeValue: "",
      currentPage4: 1,
      showSystemPopup: false,
      showApplicationPopup: false,
      showApplicationOkPopup: false,
      categoryNameValueTwo: "", //添加弹窗中的二级分类
      categoryNameValueThree: "", //添加弹窗中的三级分类
      systemPopupTitle: "",
      showLoadingGif: true,
      totalNumOfArticle: 0, //总条数
      showPageNum: 1, //要展示的页展示的页码
      example3: {
        img:
          "http://p5vegqhl6.bkt.clouddn.com/2018_04_28_14_40_09_FKmi3j7LdaxWSl8TuFOYmUjlC9DzwbDq.jpg",
        autoCrop: true,
        autoCropWidth: 200,
        autoCropHeight: 200,
        fixedBox: true,
        canMove: true,
        canMoveBox: false,
        outputSize: 0.8
      }
    };
  },
  activated() {
    this.getcategory_list();
  },
  methods: {
    //错误弹窗
    messageAlert(msg) {
      this.$message.error(msg);
    },
    getcategory_list() {
      //获取分类列表
      let _this = this;
      let ourls =
        this.urls +
        "/who/user/refreshToken/" +
        localStorage.getItem("uid") +
        "/" +
        localStorage.getItem("token");
      checkTime(
        new Date().getTime() / 1000,
        ourls,
        localStorage.getItem("reToken")
      );
      _this
        .$http({
          url:
            this.urls +
            "/who/medical/getCategoryWithMedical/" +
            localStorage.getItem("uid") +
            "/" +
            localStorage.getItem("token") +
            "/?page=" +
            this.showPageNum +
            "&category_id=" +
            this.$route.params.pid +
            "&category_level=2",
          method: "get"
        })
        .then(function(res) {
          let data = res.data;
          if (data.code == 1) {
            _this.category_list = data.data.category_list;
            _this.totalNumOfArticle = data.data.total;
            _this.showLoadingGif = false;
            localStorage.setItem("nowTimes", new Date().getTime() / 1000); //检查token失效函数
          } else {
            invalid(data.msg); //检查token失效函数
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.showPageNum = val;
      console.log(`当前页: ${val}`);
    },
    addPath(n1, n2) {
      //点击切换home-bar
      var obj = {};
      obj.n1 = n1;
      obj.n2 = n2;
      this.$store.commit("addPath", obj);
    },
    //点击申请添加分类
    clickAddCategory() {
      this.showSystemPopup = true;
      this.showApplicationPopup = true;
      this.systemPopupTitle = "申请添加分类";
    },
    //点击裁剪
    clippingPicture() {
      let _this = this;
      _this.$refs.cropper3.getCropData(data => {
        _this.example3.img = data;
      });
    },
    //点击提交
    clickSubmit() {
      let _this = this;
      let ourls =
        this.urls +
        "/who/user/refreshToken/" +
        localStorage.getItem("uid") +
        "/" +
        localStorage.getItem("token");
      checkTime(
        new Date().getTime() / 1000,
        ourls,
        localStorage.getItem("reToken")
      );
      var category_name_list = JSON.stringify([
        _this.categoryNameValueTwo,
        _this.categoryNameValueThree
      ]);
      if (
        _this.categoryNameValueTwo == "" ||
        _this.categoryNameValueThree == "" ||
        _this.drugTypeValue == ""
      ) {
        _this.messageAlert("请填写完整信息");
        return;
      }
      if (
        _this.example3.img ==
        "http://p5vegqhl6.bkt.clouddn.com/2018_04_28_14_40_09_FKmi3j7LdaxWSl8TuFOYmUjlC9DzwbDq.jpg"
      ) {
        _this.messageAlert("请上传三级分类图片");
        return;
      }
      _this.clippingPicture();
      _this
        .$http({
          url:
            this.urls +
            "/who/medical/addCategory/" +
            localStorage.getItem("uid") +
            "/" +
            localStorage.getItem("token"),
          method: "post",
          data: {
            image: _this.example3.img,
            category_name_list: category_name_list,
            pid: this.$route.params.pid,
            type: _this.drugTypeValue
          }
        })
        .then(function(res) {
          let data = res.data;
          if (data.code == 1) {
            _this.showApplicationPopup = false;
            _this.showApplicationOkPopup = true;
            localStorage.setItem("nowTimes", new Date().getTime() / 1000); //检查token失效函数
          } else {
            _this.messageAlert(data.msg);
            invalid(data.msg); //检查token失效函数
          }
        })
        .catch(function(error) {
          _this.messageAlert(error);
        });
    },
    //关闭弹窗
    hideSystemPopup() {
      this.showSystemPopup = false;
      this.showApplicationPopup = false;
      this.showApplicationOkPopup = false;
      this.categoryNameValueTwo = "";
      this.categoryNameValueThree = "";
      this.drugTypeValue = "";
      this.systemPopupTitle = "";
      this.example3.img ==
        "http://p5vegqhl6.bkt.clouddn.com/2018_04_28_14_40_09_FKmi3j7LdaxWSl8TuFOYmUjlC9DzwbDq.jpg";
    },
    //上传图片
    uploadImg(e) {
      var file = e.target.files[0];
      if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        alert("图片类型必须是jpeg,jpg,png中的一种");
        return false;
      }
      var reader = new FileReader();
      // 转化为base64
      reader.onload = e => {
        this.example3.img = e.target.result;
      };
      reader.readAsDataURL(file);
    }
  }
};
</script>
<style lang="less">
@import "../../css/drugList.less";
</style>
